package com.booking.springrestful.config;
 
import com.auth0.jwt.interfaces.Claim;
import com.booking.springrestful.utills.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
 
/**
 * JWT过滤器，拦截 /secure的请求
 */
@Slf4j
@WebFilter(filterName = "JwtFilter", urlPatterns = "/*")
public class JwtFilter implements Filter
 {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public static String frontUrl="http://localhost:5173";

     public static String adminUrl="http://localhost:5200";

     // 允许的源列表
     private static final List<String> ALLOWED_ORIGINS = Arrays.asList(
             "http://localhost:5173",
             "http://localhost:5200"
     );

     @Override
     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
         final HttpServletRequest request = (HttpServletRequest) req;
         final HttpServletResponse response = (HttpServletResponse) res;

         // 获取前端的来源地址
         String origin = request.getHeader("Origin");
         if (origin != null && isAllowedOrigin(origin)) {
             // 设置 CORS 相关的响应头
             response.setHeader("Access-Control-Allow-Origin", origin); // 允许特定的源
             response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的请求方法
             response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头
             response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许携带凭证

             // 如果是预检请求（OPTIONS），直接返回 200 状态码
             if ("OPTIONS".equals(request.getMethod())) {
                 response.setStatus(HttpServletResponse.SC_OK);
                 return;
             }
         }

         // 获取请求路径
         String path = request.getRequestURI();

         // 定义需要排除的请求路径
         boolean isExcludedPath = path.equals("/api/user/login")
                 || path.equals("/api/user/register")
                 || path.equals("/api/user/")
                 || path.equals("/api/largeModel/ask")
                 || path.equals("/api/admin/login");

         // 如果是排除的路径，直接放行
         if (isExcludedPath) {
             chain.doFilter(request, response);
             return;
         }

         response.setCharacterEncoding("UTF-8");
         // 获取 header 里的 token
         final String token = request.getHeader("Authorization");

         if (token == null) {
             response.getWriter().write("401");
             return;
         }

         // 假设这里有一个 JWT 验证工具类
         Map<String, Claim> userData = JwtUtil.verifyToken(token);
         if (userData == null) {
             response.getWriter().write("401");
             return;
         }

         Integer id = userData.get("id").asInt();
         String userName = userData.get("userName").asString();
         String password = userData.get("password").asString();

         // 拦截器拿到用户信息，放到 request 中
         request.setAttribute("id", id);
         request.setAttribute("userName", userName);
         request.setAttribute("password", password);

         chain.doFilter(req, res);
     }

     private boolean isAllowedOrigin(String origin) {
         // 检查是否在允许的源列表中
         return ALLOWED_ORIGINS.contains(origin);
     }
 
    @Override
    public void destroy() {
    }
}